﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CopySniffer.UI.Core.Core
{
    public static class ServiceLocator
    {
        private static Dictionary<Type, ActivationInfo> ActivationInfoList = new Dictionary<Type,ActivationInfo>();

        public static void RegisterType(Type toType, Type fromType)
        {
            ActivationInfoList.Add(toType, new ActivationInfo(toType, fromType));
        }

        public static void RegisterType(Type toType, Func<object> factoryMethod)
        {
            ActivationInfoList.Add(toType, new ActivationInfo(toType, factoryMethod));
        }

        public static void RegisterType(Type toType, object instance)
        {
            ActivationInfoList.Add(toType, new ActivationInfo(toType, instance));
        }

        public static T GetService<T>()
        {
            return (T) ActivationInfoList[typeof(T)].GetObject();
        }

        private class ActivationInfo
        {
            public ActivationInfo(Type toType, Type fromType)
            {
                ToType = toType;
                FromType = fromType;
            }

            public ActivationInfo(Type toType, Func<object> factoryMethod)
            {
                ToType = toType;
                FactoryMethod = factoryMethod;
            }

            public ActivationInfo(Type toType, object instance)
            {
                ToType = toType;
                Instance = instance;
            }

            public Type ToType { get; private set; }
            public Type FromType { get; private set; }
            public Func<object> FactoryMethod { get; private set; }
            public object Instance { get; private set; }

            public object GetObject()
            {
                if (Instance != null)
                    return Instance;
                if (FactoryMethod != null)
                    return FactoryMethod();
                return Activator.CreateInstance(ToType);
            }

        }
    }


}
